<?php
namespace app\erp\controller;

use app\admin\model\BdDatacenter;
use app\admin\model\BdOrg;
use app\admin\model\Porder;
use app\admin\model\Synlogs;
use Curl\Curl;
use think\Cache;
use think\Log;
use traits\controller\Jump;
class Base


{
    use Jump;

    protected $url                      = "http://113.140.31.86:8022/ierp/kapi/";
    protected $client_id;
    protected $client_secret;
    protected $account_id;
    protected $user_name;
    //过期时长 秒
    protected $cache_access_token_time          = 6600;//6600;
    //刷新过期时长
    protected $cache_refresh_access_token_time  = 6800;
    //缓存key
    protected $cache_access_token_name;

    protected $cache_refresh_access_token_name;



    protected $token;
    protected $curl;
    protected $org;

    protected $starttime;
    protected $endtime;
    protected $pageSize = 1000;
    protected $pageNo   = 1;
    protected $datacenter_data = [];

    public function __construct($client_id,$client_secret,$account_id,$user_name)
    {
        $this->client_id            = $client_id;
        $this->client_secret        = $client_secret;
        $this->account_id           = $account_id;
        $this->user_name            = $user_name;

        $this->getDatacenterData();

//        switch ($this->account_id)
//        {
//            case 1845044874454237184:
//                $this->url = "https://pt.metalscloud.com:8765/kapi/";
//                break;
//            case 1842944793479483392:
//                $this->url = "https://jcx.metalscloud.com:8765/kapi/";
//                break;
//            case 2117551759156052992:
//                $this->url = "https://jcx.metalscloud.com:8765/kapi/";
//                break;
//        }
        $this->url = $this->datacenter_data['fk_bdl_url'];


        $this->cache_access_token_name          = now_domain() . 'bdl_access_token' . '_' . $this->account_id;
        $this->cache_refresh_access_token_name  = now_domain() . 'bdl_refresh_access_token' . '_' . $this->account_id;

        $this->curl     = new Curl();
        $this->token    = $this->getToken();

        $this->org      = $this->getBdorg();

    }

    public function getBdorg()
    {
        return BdOrg::where('fk_bdl_bd_datacenter',$this->account_id)->order('id','asc')->select();
    }

    protected function getDatacenterData()
    {
        $data = BdDatacenter::where('fnumber',$this->account_id)->find();

        $this->datacenter_data = $data;
    }

    public function getToken()
    {
        $access_token = $this->getAccessTokenFromCache();


        if ($access_token) {
            return $access_token;
        }


        $refresh_token = $this->getRefreshTokenFromCache();

        if ($refresh_token) {
            if ($this->refreshToken($refresh_token)) {
                return $this->getAccessTokenFromCache();
            }
        } else {
            $res = $this->accessToken();
            if ($res['code'] == 1)
            {
                return $this->getAccessTokenFromCache();
            }else{
                $this->error($res['msg']);
            }
        }
    }



    public function accessToken()
    {
        $method         = "oauth2/getToken";

        $fullurl        = $this->url . $method;

        $response_data = [
            'client_id'                     => $this->client_id,
            'client_secret'                 => $this->client_secret,
            'username'                      => $this->user_name,
            'accountId'                     => $this->account_id,
            'nonce'                         => uuid(),
            'timestamp'                     => date("Y-m-d H:i:s"),
            'language'                      => "zh_CN"
        ];

        $curl = new Curl();

        $curl->setHeader("Content-Type", "application/json");

        $res = $curl->post($fullurl, json_encode($response_data));


        if(property_exists($res,'status'))
        {
            if($res->status == 1)
            {
                //加入缓存
                cache($this->cache_access_token_name, $res->data->access_token, $this->cache_access_token_time);
                //替换值即可
                cache($this->cache_refresh_access_token_name, $res->data->refresh_token,$this->cache_refresh_access_token_time);

                return [
                    'code'  => 1,
                ];
            }else{
                $msg = property_exists($res,'message') ? $res->message : '';
                $des = property_exists($res,'description') ? $res->description : '';
                return [
                    'code'  => 0,
                    'msg'   => $msg . $des,
                ];
            }


        }else{
            $msg = property_exists($res,'message') ? $res->message : '';
            $des = property_exists($res,'description') ? $res->description : '';
            return [
                'code'  => 0,
                'msg'   => $msg . $des,
            ];
        }
    }


    public function refreshToken($refresh_token)
    {
        $method         = "oauth2/refreshToken";

        $fullurl        = $this->url . $method;

        $response_data = [
            'client_id'                     => $this->client_id,
            'grant_type'                    => 'refresh_token',
            'refresh_token'                 => $refresh_token,
            'accountId'                     => $this->account_id,
            'nonce'                         => uuid(),
            'timestamp'                     => date("Y-m-d H:i:s",strtotime('-5 minutes')),
        ];

        $curl = new Curl();

        $curl->setHeader("Content-Type", "application/json");

        $res = $curl->post($fullurl, json_encode($response_data));

        if($res->status == 1)
        {
            //加入缓存
            cache($this->cache_access_token_name, $res->data->access_token, $this->cache_access_token_time);
            //替换值即可
            cache($this->cache_refresh_access_token_name, $res->data->refresh_token,$this->cache_refresh_access_token_time);

            return true;
        }else{
            return 'refresh token error';
        }

    }


    protected function getAccessTokenFromCache()
    {
        return cache($this->cache_access_token_name);
    }

    protected function getRefreshTokenFromCache()
    {
        return cache($this->cache_refresh_access_token_name);
    }






}